from util.util_image import load_image_from_path, load_image_from_bytes, calculate_ssim, evaluate_ssim


# 检查是否有得分图片
def parse_images(list_image, target_image_data):
    ssim_list = []
    for image in list_image:
        image_data = load_image_from_bytes(image)
        ssim = calculate_ssim(image_data, target_image_data)
        # print("ssim:", ssim, evaluate_ssim(ssim))
        ssim_list.append(ssim)
    return ssim_list


class ScorerPart3:
    ANS_IMG_PATH_LIST_PART_3 = [f"files/ans/ans_3_1.png"]

    def __init__(self):
        self.ans_img_list_part_3 = []
        for path in self.ANS_IMG_PATH_LIST_PART_3:
            self.ans_img_list_part_3.append(load_image_from_path(path))

    # 报告判分: 第三部分
    def score_part_3(self, dict_matched_paragraphs, list_matched_images):
        score = 0
        ssim = 0
        # 检查是否有得分图片
        try:
            for target_img_data in self.ans_img_list_part_3:
                ssim_list = parse_images(list_matched_images, target_img_data)
                print("ssim_list:", ssim_list)
                # 有一张图相似度到阈值, 算得分
                if len(ssim_list) > 0 and max(ssim_list) > 0.5:
                    score = 1
                    ssim = max(ssim_list)
                    print("part 3: 得分, ssim_max:", max(ssim_list))
                    break
        except Exception as e:
            print(f"第3部分判分出错: {e}")
        return score, ssim